﻿@{
    // Initialiser les variables de la page générale
    var toSearch = "";

    Validation.RequireField("Contact", "You have to specify a title.");

    if (IsPost)
    {
        AntiForgery.Validate();
        toSearch = Request.Form["contact"];

        // Si toutes les informations sont valides, créer un compte
        if (Validation.IsValid())
        {
            // Insérer un nouvel utilisateur dans la base de données
            var dbcontext = new alguillet_ExpenseManagerEntities();

            var relations = dbcontext.MembersRelations;

            //int nb = dbcontext.Members.Where(User => User.Login == toSearch).Count();

            var members = dbcontext.Members.Where(User => User.Login == toSearch);

            if (members.Count() == 1)
            {
                MembersRelation rel = new MembersRelation();
                rel.IDFRequester = WebSecurity.CurrentUserId;
                var contact = (from o in dbcontext.Members.Where(User => User.Login == toSearch || User.Email == toSearch) select o);
                foreach (var item in contact)//Here the list is loaded fully
                {
                    rel.IDFRequested = item.IDMember;
                }
                rel.Status = 0;

                relations.Add(rel);
                var success = dbcontext.SaveChanges();

                if (success < 1)
                {
                    ModelState.AddFormError("Une erreur est survenue.");
                }
            }
        }
    }
}

<form method="post" >
@AntiForgery.GetHtml()
@Html.ValidationSummary("Friend request failed.", excludeFieldErrors: true, htmlAttributes: null)
<fieldset>
    <legend>Friend request</legend>
    <ol>
        <li>
            <label for="contact">
                Login or email</label>
            <input type="text" id="contact" name="contact" @Validation.For("Contact") />
            @Html.ValidationMessage("title")
        </li>
    </ol>
    <input type="submit" value="Add"/>
</fieldset>
</form>
<script type="text/javascript">
    $(document).ready(function () {
        $("#value").spinner({
            step: 1.00,
            numberFormat: "n"
        });
    });
</script>